package com.caine.ts.ch18;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.caine_ts.R;

public class Lesson18_1 extends Activity {

	private Button btn_start = null;
	private ProgressBar pbar_1 = null;
	private ProgressBar pbar_2 = null;
	private int index = 0;
	private int index1 = 0;
	private boolean flags = false;
	private Timer timer = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lesson18_1);
		// init();

	}

	void init() {
		btn_start = (Button) findViewById(R.id.btn_start);
		pbar_1 = (ProgressBar) findViewById(R.id.pbar_1);
		pbar_2 = (ProgressBar) findViewById(R.id.pbar_2);

		btn_start.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Message message = new Message();
				message.what = 0x113;
				handler1.sendMessageDelayed(message, 1000);
				if (!flags) {
					flags = true;

					timer = new Timer();
					timer.schedule(new TimerTask() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							Message message1 = new Message();
							message1.what = 0x119;
							handler2.sendMessageDelayed(message1, 1000);
							System.out.println("handler2.sendMessageDelayed(message1, 1000);");
						}
					}, 0, 1000);

				}
			}
		});

	}

	private Handler handler1 = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0x113) {
				if (index >= 100) {
					index = 0;
					pbar_1.setProgress(index);					
					
				}
				pbar_1.setProgress(index += 10);
				System.out.println("pbar_1.setProgress :" + index);
			}
		};
	};

	private Handler handler2 = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0x119) {
				if (index1 >= 100) {
					index1 = 0;
					pbar_2.setProgress(0);					
					timer.cancel();
					flags = false;
					showMsg("Loading OK!");
					System.out.println("timer.cancel();");
				}else{
				pbar_2.setProgress(index1 += 5);
				System.out.println("pbar_2.setProgress :" + index1);
				}
			}
		};
	};

	@Override
	protected void onPause() {
		timer.cancel();
		super.onPause();
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		timer.cancel();
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		init();
	}
	
	private void showMsg(String msg){
		Toast.makeText(Lesson18_1.this, msg, Toast.LENGTH_SHORT).show();
	}
}
